package com.zhao.util;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class SystemLogUtil {
    private static final Logger logger=Logger.getLogger(SystemLogUtil.class);

    @AfterThrowing(pointcut = "execution(* com.zhao.service.*.*(..))",throwing = "e")
    public void doLog(JoinPoint joinPoint, Exception e){
        //把错误信息通过log4j 写出到文件
//        String methodName = joinPoint.getSignature().getName();
        //写出捕捉到的异常信息
//        logger.error(methodName+"出现"+e.getMessage()+"异常");
        //获取异常详情
        StackTraceElement[] stackTrace = e.getStackTrace();
        for (StackTraceElement ste :stackTrace) {
            String className = ste.getClassName();//java 的class文件名
            String fileName = ste.getFileName();//出现错误的文件名
            int lineNumber = ste.getLineNumber();//哪一行出错
            String methodName1 = ste.getMethodName();//哪个方法出了异常
            logger.error(className+" 类的 "+methodName1+" 方法在 "+lineNumber+" 行出现 "+e.getMessage()+" 异常"+"(所在文件："+fileName+")");
        }

    }
}
